import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'

import { getMenuMes } from '@/api/user'
import Layout from '@/layout'
import userCom from '@/views/user/index.vue'
import roleCom from '@/views/role/index.vue'
import menuCom from '@/views/menu/index.vue'
import store from '@/store'

const state = {
  token: getToken(), // 从缓存中读取初始值
  userInfo: {}, // 存储用户基本资料状态
  routesSiderBar: constantRoutes, // 静态路由的数组
  routes: []
}

const mutations = {
  setToken(state, token) {
    state.token = token
    // 同步到缓存
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routesSiderBar = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  }
}

const loadView = (componentPath) => {
  // 需要配置
  if (componentPath === '/user/index.vue') {
    return userCom
  }
  if (componentPath === '/role/index.vue') {
    return roleCom
  }
  if (componentPath === '/menu/index.vue') {
    return menuCom
  }
}

const transformRoutes = (backendRoutes) => {
  return backendRoutes.map(route => {
    const transformedRoute = {
      path: route.path,
      name: route.name,
      meta: {
        title: route.meta.title,
        icon: route.meta.icon
      },
      // 单独一项子项 展示菜单分类
      alwaysShow: route.children && route.children.length > 0,
      hidden: route?.status === 1
    }

    // 处理组件
    if (route.component) {
      transformedRoute.component = loadView(route.component)
    }

    // 递归处理子路由
    if (route.children && route.children.length > 0) {
      transformedRoute.children = transformRoutes(route.children)
    }
    return transformedRoute
  })
}

const actions = {
  async generateRoutes({ commit }, menuData) {
    // 接口
    const oldresult = await getMenuMes({
      project_name: 'login_platform'
    })
    let dynamicRoutes = transformRoutes(oldresult)
    const menuList = JSON.parse(JSON.stringify(dynamicRoutes))

    // 侧边栏菜单
    store.commit('user/setRoutes', menuList)
    // 处理为项目需要的layout格式
    dynamicRoutes = dynamicRoutes.map(item => {
      if (item.children && item.children.length > 0) {
        const obj = {
          path: item.path,
          component: Layout,
          children: item.children
        }
        return obj
      } else {
        const obj = {
          path: '/',
          component: Layout,
          hidden: true,
          children: [item]
        }
        return obj
      }
    })
    commit('SET_ROUTES', dynamicRoutes)
  },

  async login(context, data) {
    const result = await login(data)
    context.commit('setToken', result.token)
    context.commit('setUserInfo', result.user)
    return result
  },
  // 获取用户的基本资料
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result
  },
  // 退出登录的action
  logout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})
    // 清空动态路由
    context.commit('SET_ROUTES', [])
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
